package net.didactylos.helpline.action;

import java.util.*;

import org.hibernate.*;
import org.hibernate.exception.ConstraintViolationException;

import net.didactylos.helpline.data.*;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.*;

public class UsersAction extends HelplineActionBean
{
    @ValidateNestedProperties({
        @Validate(field="username", required=true, maxlength=50, on="addUser"),
        @Validate(field="firstNames", required=true, maxlength=50, on="addUser"),
        @Validate(field="lastName", required=true, maxlength=50, on="addUser"),
        @Validate(field="emailAddress", required=true, maxlength=50, converter=EmailTypeConverter.class, on="addUser")
    })
	private User newUser;
    
    @ValidateNestedProperties({
        @Validate(field="name", required=true, on="addRole"),
        @Validate(field="capabilities", required=true, on="addRole")
    })
    private Role newRole;
    
    private long roleId;
    
	private List<User> users;
	private List<Role> roles;
	
	public User getNewUser()
	{
		return newUser;
	}

	public void setNewUser(User newUser)
	{
		this.newUser = newUser;
	}
	
	public Role getNewRole()
	{
		return newRole;
	}

	public void setNewRole(Role newRole)
	{
		this.newRole = newRole;
	}

	public long getRoleId()
	{
		return roleId;
	}

	public void setRoleId(long roleId)
	{
		this.roleId = roleId;
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers()
	{
		if (users == null)
		{
			Session session = getContext().getSession();
			users = session.createCriteria(User.class).list();
		}
		return users;
	}
	
	@SuppressWarnings("unchecked")
	public List<Role> getAllRoles()
	{
		if (roles == null)
		{
			Session session = getContext().getSession();
			roles = session.createCriteria(Role.class).list();
		}
		return roles;
	}
	
	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.SIGN_IN)
	public Resolution view()
	{
		return new ForwardResolution("users.jspx");
	}

	@Secured(Capabilities.SIGN_IN)
	public Resolution addUser()
	{
		Session session = getContext().getSession();

		Role role = (Role) session.get(Role.class, roleId);
		if (role == null)
		{
			ValidationError error = new LocalizableError(
					"validation.expression.valueFailedExpression", "roleId", roleId);
            getContext().getValidationErrors().add("roleId", error);
            return getContext().getSourcePageResolution();
		}
		
		newUser.setRole(role);
		String password = newUser.generatePassword(10);

		try
		{
			session.save(newUser);
		}
		catch (ConstraintViolationException e)
		{
			ValidationError error = new LocalizableError("userExists");
            getContext().getValidationErrors().add("newUser.username", error);
            return getContext().getSourcePageResolution();
		}
        
		getContext().getMessages().add(new LocalizableMessage("addUserMessage", newUser.getUsername(), password));
		return new RedirectResolution(UsersAction.class);
	}
	
	@Secured(Capabilities.SIGN_IN)
	public Resolution addRole()
	{
		Session session = getContext().getSession();
		session.save(newRole);
        
        getContext().getMessages().add(new LocalizableMessage("addRoleMessage", newRole.getName()));

		return new RedirectResolution(UsersAction.class);
	}

}
